<template>
  <div class="value-page">
    <questionnaire-core-audit-page 
    :parentProjectBuildId="projectBuildId" 
    :changeId="changeId"  
    v-if="!canDoSave || needReload">
    </questionnaire-core-audit-page>
    <div class="question-list" v-else>
      <div v-for="group in questionList">
        <ul v-for="page in group">
          <div v-show="currStartQuestionId == page[0].id">
            <question-list
              :question-list-data="page"
              :project-build-id="projectBuildId"
              :bus-field-val="changeId ? 'ProjectBuildValueChange' : 'ProjectBuildValue'"
              :bus-key-val="changeId ? projectBuildId+'_'+changeId : projectBuildId"
              v-on:jumpNextPage="jumpNextPage"
              v-on:clearnQuestion="clearnQuestion($event)"  
              @showAttach="showAttach"
              @downLoadAttach="downLoadAttach" 
              @questChange="judgeResult=false"
            ></question-list>

            <div style="widht: 80%; height: 30px; display: none" v-show="judgeResult">
              <img src="@/assets/category.png" alt="" />
              <span>&nbsp;&nbsp;<b>评定结果</b></span>
            </div>
            <div class="judge-result" v-show="judgeResult">
              <div style="width: 100%; border-right: 1px solid rgb(237, 237, 237)">
                <b>项目立项评定结果</b>&nbsp;&nbsp;&nbsp;&nbsp; 项目等级：<span class="result-show"
                  ><b>{{ projectLevel }}</b></span
                >&nbsp;&nbsp;&nbsp;&nbsp; 核心力得分：<span class="result-show"
                  ><b>{{ projectGradePointCore }}分</b></span
                >&nbsp;&nbsp;&nbsp;&nbsp;
              </div>
            </div>

            <div class="btnBox">
              <a-button  v-show="!(currGroupIndex == 0 && currPageIndex == 0) && showBtn" @click="nextDo('pre')">上一步</a-button>
              <a-button style="margin: 0 auto" v-if="!hadNext && showBtn" type="primary" @click="doSubmit()">保存试题</a-button>
              <a-button style="margin: 0 auto" v-if="hadNext && showBtn" type="primary" @click="nextDo('next')">下一步</a-button>
              <a-button v-if="currentAudit&&!questionNeverChange" type="primary" @click="runTest">重跑价值表</a-button>
            </div>
          </div>
        </ul>
      </div>
    </div>
    <a-back-top style="right:50px;" />
    <div class="btnBox floatNav" v-if="canDoSave&&!questionNeverChange">
        <a-button  @click="runTest">重跑试题</a-button>
    </div> 
    <a-modal title="温馨提示" :visible="confirmVisible" @ok="confirmJumpOk" @cancel="confirmJumpCancel">
      <p>亲，当前修改的题目涉及到后面题目的跳转题目，如需修改将会清空后面已作答过的题目，请确认是否清空？</p>
    </a-modal>

    <a-modal title="温馨提示" :visible="reloadVisible" @ok="reloadQuesions" @cancel="reloadVisible = false">
      <p>该项目类型的核心力值价值表题目有变更，请确认是否放弃当前作答内容，加载最新版题目，重新作答？<br>
         确定：自动会自动清理题目，重新加载新题目，重新作答<br>
         取消：会继续保留现有作答题目。如果未保存现有的答题内容，请先点击取消，保存作答内容到本地。</p>
    </a-modal>

    <a-modal
      v-model="visibleModelRemind"
      dialogClass="hte-mes-modal"
    >
      <div slot="title"><a-icon type="alert" />温馨提示</div>
      <div class="ant-mes-modal-body">
        <p>有符合的才需要回答，无符合的不需要回答。</p>
        <p>每次点下一步时，系统自动保存答题，下次进入还会看到已答的题目。</p>
        <p>已答过的题目返回修改，影响后面题目跳转的，系统会提示后面的题目需要清空才可以重新答题。</p>
        <p>有历史版本，答完的题目由于管理者更新题目版本，进入后会提示重新加载新版题目，原来的题目会进入历史版本。</p>
        <p>答题说明的文本框是红色，表示这道题必须填写说明，题目出现“上传附件”表示这道题必须上传附件证明达成的效果。</p>
        <p>谨慎答题，避免随意测试，随机套题的情况。</p>
      </div>
      <div slot="footer">
        <a-button type="primary" @click="valueVisibleModelRemind()">确定</a-button>  
      </div>
    </a-modal>

    <a-modal title="历史版本" :visible="hist.visible" @ok="hist.visible = false" @cancel="hist.visible = false" :width = "600" :destroyOnClose="true">
      <a-table
        :columns="hist.columns"
        :data-source="hist.data"
        bordered
        style="padding-bottom: 40px; border-bottom: 1px solid #f0f0f0"
      >
      <template slot="version" slot-scope="text, record">
        V-{{text}}
      </template>
      <template slot="toDo" slot-scope="text, record">
        <a-button type="primary" size="small" @click="showHistDetail(record)">详细</a-button> 
      </template>
      </a-table>
    </a-modal>
    <a-modal title="历史详细" :visible="hist.visibleDeatil" @ok="hist.visibleDeatil = false" @cancel="hist.visibleDeatil = false" width = "80vw" :height = "800" :destroyOnClose="true">
      <questionnaire-core-audit-page :parentProjectBuildId="projectBuildId" :version="hist.version"></questionnaire-core-audit-page>
    </a-modal>

  </div>
</template>

<script>
import $ from 'jquery'
import '@/utils/upload.install.js'
import { objNotNull,getParamValFromUrl } from '@/utils/common.js'
import { getAction, postAction, postActionAsync,previewAttach } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { formatFileSize, endWith, arrNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'

export default {
  name: 'QuestionListFather',
  components: {
    QuestionList: () => import('@/components/tools/QuestionCoreList'),
    QuestionnaireCoreAuditPage: () => import('@/components/tools/projectBuild/QuestionnaireCoreAuditPage'),
  },
  data() {
    return {
      typeCore: 'core',
      projectBuildId: '',
      projectBuild: {},
      judgeResult: false,
      tabbarstyle: {
        backgroundColor: '#fff',
        position: 'fixed',
        height: 'unset',
      },
      currGroupIndex: 0,
      currPageIndex: 0,
      currStartQuestionId: 0,
      quesitonShowList: [],
      questionList: [],
      preQuestionList: [],
      oldQuestions: [],
      coreTest: null,
      coreGroupQuestionList: [],
      hadNext: false,
      CoreAnswer: {
        valueQuestions: [],
        testResult: '',
        valueType: 'core',
        projectBuildId: '',
        testList: ''
      },
      url: {
        getBuildQuestions: '/valueTest/getBuildQuestions',
        queryTestValueById: '/projectBuild/queryTestValueById',
        saveValueTest: '/projectBuild/saveValueTest',
        computeTestResult: '/projectBuild/computeTestResult',
        reloadQuesions: '/projectBuild/reloadQuesions',
        downLoadBatch: '/common/downLoadBatch',
        getProjectBuildTestHist: '/projectBuild/getProjectBuildTestHist',
        valueVisibleModelRemind: '/projectBuild/valueVisibleModelRemind'
      },
      //评定结果
      projectLevel: '',
      projectGradePointCore: 0,
      //确认跳转
      confirmVisible: false,
      confirmJumpId: 0,
      confirmQuestionId: 0,
      confirmOldOptionId: 0,
      addJumpFresh: false,
      //重跑
      reloadVisible: false,
      needReload: false,
      //显示操作按钮
      showBtn: true,
      nextArea: false,
      hist: {
        visible: false,
        visibleDeatil: false,
        version: '',
        columns: [
          {
            title: '版本号',
            dataIndex: 'version',
            width: '20%',
            scopedSlots: { customRender: 'version' },

          },
          {
            title: '删除人',
            dataIndex: 'delUserId'
          },
          {
            title: '删除时间',
            dataIndex: 'delTime'
          },
          {
            title: '操作',
            dataIndex: 'id',
            width: '20%',
            scopedSlots: { customRender: 'toDo' },

          },
        ],
        data: [],
        currentAudit:false,
      },
      visibleModelRemind:false,
      canDoSave:false,
      changeId:'',
      projectRewardApplyId:'',
      questionNeverChange:false
    }
  },
  mounted() {
    this.projectBuildId = getParamValFromUrl('projectBuildId')
    var groupIndex = getParamValFromUrl('currGroupIndex')
    var pageIndex = getParamValFromUrl('currPageIndex')
    var currentAudit = this.$route.query.currentAudit
    this.currentAudit = currentAudit == 'true' ? true : false
    this.changeId = this.$route.query.changeId
    this.projectRewardApplyId = this.$route.query.projectRewardApplyId;
    this.currGroupIndex = groupIndex == '' ? 0 : parseInt(groupIndex)
    this.currPageIndex = pageIndex == '' ? 0 : parseInt(pageIndex)
    this.CoreAnswer.projectBuildId = this.projectBuildId
    var canDoSave = getParamValFromUrl('canDoSave')
    this.canDoSave = canDoSave=='true' ? true : false
    debugger
    if(this.changeId && !this.canDoSave){
      return;
    }
    this.queryTestValue()
  },
  created() {},
  computed: {},
  methods: {
    valueVisibleModelRemind(){
      this.visibleModelRemind = false;
      getAction(this.url.valueVisibleModelRemind, { id: this.projectBuildId}).then((res) => {
        if (res.code == 200) {
        } else {
          this.$message.warning('更新确认提示有误:' + res.message)
        }
      }).catch(res =>{
        this.$message.warning('更新确认提示异常:'+res.message);
      });
    },
    showHistDetail(record){
      this.hist.visibleDeatil=true;
      this.hist.version=record.version;
    },
    showHist(){
      getAction(this.url.getProjectBuildTestHist, { projectBuildId: this.projectBuildId,type:'core' }).then((res) => {
        if (res.code == 200) {
          this.hist.data = res.result;
          this.hist.data.forEach(item=>item.key=item.id);
          this.hist.visible = true;
        } else {
          this.$message.warning('加载价值表历史版本信息出错:' + res.message)
        }
      }).catch(res =>{
        this.$message.warning('加载价值表历史版本信息异常:'+res.message);
      });
    },
    showAttach(record) {
      var id = record.id
      var uploader = record.uploader
      var fileName = record.fileName
      if (!this.checkPermisson(uploader) && !this.projectBuild.projectSubTypeAdmin) {
        this.$message.warning('仅有该项目管理员、附件上传人、项目经理、副经理可以查看!')
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.doDownLoadBatch(id)
        return
      }
      let params={
        id:id,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        if (this.projectBuild.projectClass == '40' || this.projectBuild.projectClass == '61') {
          window.open(process.env.BASE_URL+'/pdf/web/normalViewer.html?file=' + url)
        } else {
          window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
        }
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    downLoadAttach(record){
      var id = record.id
      var uploader = record.uploader
      if (!this.checkPermisson(uploader) && !this.projectBuild.projectSubTypeAdmin) {
        this.$message.warning('仅有该项目管理员、附件上传人、项目经理、副经理可以下载!')
        return
      }
      this.doDownLoadBatch(id)
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      var href =
        this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    checkPermisson(uploader) {
      var projectManagers = this.projectBuild.projectManagers
      var assistantProjectManagers = this.projectBuild.assistantProjectManagers
      var currUser = Vue.ls.get(USER_INFO).username
      if (uploader == currUser) {
        return true
      }
      if (projectManagers == null || projectManagers.length == 0) {
        projectManagers = []
      }
      projectManagers = projectManagers.concat(assistantProjectManagers)
      if (projectManagers.indexOf(currUser) > -1) {
        return true
      }
      return false
    },
    cancelEnterCore() {
      var url =
        this.HTE_OLD_SERVER_URL +
        '/projectBuild/buildTime?bootToken=' +
        Vue.ls.get(ACCESS_TOKEN) +
        '&id=' +
        this.projectBuildId
      window.location.href = url
    },
    runTest(){
      let that = this
      Modal.confirm({
        content: '重跑试题将把当前答题置为历史版本，确定重跑试题？',
        onOk: () => {
          that.reloadQuesions();
        },
      })
    },
    //重跑价值表
    reloadQuesions() {
      getAction(this.url.reloadQuesions, { id: this.projectBuildId,type:'core',changeId:this.changeId }).then((res) => {
        if (res.code == 200) {
          window.location.reload()
        } else {
          this.$message.warning('重置失败:' + res.message)
        }
        this.reloadVisible = false
      })
    },
    //查询题目数据，初始化
    queryTestValue() {
      debugger
      var vm = this 
      vm.CoreAnswer.projectBuildId=this.projectBuildId;
      getAction(this.url.queryTestValueById, { id: this.projectBuildId,type:'core',changeId: this.changeId}).then((res) => {
        var result = res.result
        if (result == null) {
          this.$message.warning(res.message)
        } else {
          debugger
          if (result.projectLevel != null && result.projectLevel.length > 0) {
            vm.nextArea = true
          }
          vm.projectBuild = result;
          vm.visibleModelRemind = !vm.projectBuild.valueRemind
          vm.coreTest = result.coreTest
          if(vm.coreTest!=null && vm.coreTest.length>0){
            vm.CoreAnswer.testList = JSON.stringify(vm.coreTest)
          }
          var initFromResult = result.projectBuildTestVOList != null && result.projectBuildTestVOList.length > 0
          if (initFromResult) {
            //编辑过，取已编辑信息
            result.projectBuildTestVOList.map((test) => {
              if (test.valueQuestions != null && test.valueQuestions.length > 0 && test.valueType == 'core') {
                vm.questionList = vm.questionList.concat(test.valueQuestions)
              }
            })
            vm.oldQuestions = JSON.parse(JSON.stringify(this.questionList))
            vm.initQuestionList()
          } else {
            vm.initQuestionList()
          }
          debugger
          if(this.canDoSave && result.coreQuestionChangeFlag){
            vm.reloadVisible = true
            vm.needReload = true;
          }
          this.questionNeverChange=!!result.questionNeverChange;
        }
        console.log('vm.questionList:' + JSON.stringify(vm.questionList))
      })
    },
    //初始化
    initQuestionList() {
      if (this.coreTest != null && this.coreTest.questionTree != null && this.coreTest.questionTree.length > 0) {
        this.castTreeToGroupQuestionList(this.coreTest.questionTree, this.typeCore)
        if (this.questionList.length == 0) {
          this.coreGroupQuestionList.forEach((questions) => {
            var nextQuestions = this.getNextPageQuestions(questions, questions[0].id)
            this.questionList.push([nextQuestions])
          })
        }
      }
      if (this.questionList.length > 0) {
        this.freshPreQustionList()
        var level = this.projectBuild.projectLevel;
        var corePoint = this.projectBuild.projectGradePointCore;
          if(this.projectBuild.status>1 ){
            if(objNotNull(this.projectBuild.projectAuditLevel)){
              level = this.projectBuild.projectAuditLevel;
            }
            if(objNotNull(this.projectBuild.projectAuditGradePointCore)){
              corePoint = this.projectBuild.projectAuditGradePointCore;
            }
          }
        //如果已有项目等级和绩点，则默认展示最后一页
          if (level != null 
          &&corePoint>0 ){
            // this.currGroupIndex=this.questionList.length-1;
            // this.currPageIndex=this.questionList[this.currGroupIndex].length-1;
            this.projectLevel = level
            this.projectGradePointCore = corePoint
            this.judgeResult = true
          }
        this.currStartQuestionId = this.questionList[this.currGroupIndex][this.currPageIndex][0].id
        if (this.currGroupIndex<(this.questionList.length-1)  ||  this.currPageIndex<this.questionList[this.currGroupIndex].length-1) {
          this.hadNext = true
        }
      }
    },
    //树状结构数据转为组状
    castTreeToGroupQuestionList(treeList, type) {
      var vm = this
      if (!treeList || !type) {
        return
      }
      treeList.forEach((tree) => {
        var questions = []
        vm.initCurrGroupQuestions(tree, questions)
        vm.sortQuestions(questions)
        if (questions.length > 0) {
          vm.setSourceQuestions(vm.coreGroupQuestionList, questions)
        }
      })
    },
    initCurrGroupQuestions(question, questions) {
      var vm = this
      var notIn = true
      questions.forEach((quest) => {
        if (quest.questionNum == question.questionNum) {
          notIn = false
        }
      })
      if (notIn) {
        questions.push(question)
      }
      if ((question.questionType == 1 || question.questionType == 4) && question.questionList != null) {
        question.questionList.forEach((quest) => {
          vm.initCurrGroupQuestions(quest, questions)
        })
      }
    },
    //对每组数据排序
    sortQuestions(questions) {
      questions = questions.sort(function (a, b) {
        if (a.orderNum < b.orderNum) {
          return -1
        } else if (a.orderNum > b.orderNum) {
          return 1
        } else {
          return 0
        }
      })
    },
    //合并连续无跳转问题
    setSourceQuestions(list, questions) {
      if (list == null || questions == null || questions.length < 1) {
        return
      }
      if (list.length < 1 || questions.length > 1) {
        list.push(questions)
      } else {
        var last = list[list.length - 1]
        var addGroup = false
        last.forEach((quest) => {
          if (this.hadNextQuestionType(quest.questionType) && !quest.relateTechnologyLibFlag) {
            for (var j = 0; j < quest.optionVoList.length; j++) {
              var option = quest.optionVoList[j]
              if (option.jumpQuestionId != null && option.jumpQuestionId > 0) {
                //包含跳转的，为一页
                addGroup = true
              }
            }
          }
        })
        if (addGroup) {
          list.push(questions)
        } else {
          list[list.length - 1] = last.concat(questions)
        }
      }
    },
    //跳转下一页
    jumpNextPage(questionId, optionId) {
      var vm = this
      var jumpId = 0
      var question = vm.getQuestionFromSource(questionId)
      question.optionVoList.forEach((option) => {
        if (option.id == optionId) {
          jumpId = option.jumpQuestionId
        }
      })
      console.log('get next changed>questionId:' + questionId + 'jumpId:' + jumpId)
      var oldOptionId = 0
      vm.preQuestionList[vm.currGroupIndex][vm.currPageIndex].forEach((quest) => {
        if (quest.id == questionId) {
          oldOptionId = vm.getQuestVal(quest)
        }
      })

      if (oldOptionId > 0 && optionId != oldOptionId) {
        console.log('do next changed>questionId:' + questionId + 'jumpId:' + jumpId)
        this.confirmJumpId = jumpId
        this.confirmQuestionId = questionId
        this.confirmOldOptionId = oldOptionId
        this.confirmVisible = true
      } else {
        vm.addJumpQuestion(jumpId)
      }
    },
    //添加跳转问题
    addJumpQuestion(jumpQuestionId) {
      if (jumpQuestionId == null || jumpQuestionId == 0) {
        return
      }
      var quest = this.getQuestionFromSource(jumpQuestionId)
      if (quest == null) {
        this.$message.warning('跳转问题id【' + jumpQuestionId + '】无效')
      }
      console.log('group:' + this.currGroupIndex + 'page:' + this.currPageIndex + 'push quest:' + JSON.stringify(quest))
      this.questionList[this.currGroupIndex][this.currPageIndex].push(quest)
      this.freshPreQustionList()
      //不知为何，清空后，再次添加无法重新渲染页面，跳转刷新
      if (this.addJumpFresh) {
        this.saveAndNext('fresh')
      }
    },

    //重置跳转选项
    resetJumpQuestion(questionId, answer) {
      this.questionList[this.currGroupIndex][this.currPageIndex].forEach((quest) => {
        if (quest.id == questionId) {
          if (quest.questionType == 1) {
            quest.singleChoice = answer
          }
          if (quest.questionType == 4) {
            quest.trueOrFalse = answer
          }
        }
      })
    },
    //保存问卷,进行下一步
    async saveAndNext(type) {
      var submitresult=0;
      this.showBtn = false
      var vm = this
      vm.CoreAnswer.valueQuestions = vm.questionList
      //保存或提交，计算分数
      var computeProjectLevel = false
      if (type === 'save' || this.currentAudit) {
        computeProjectLevel = true
      }
      if(!this.changeId){
        this.changeId='';
      }
      if(!this.projectRewardApplyId){
        this.projectRewardApplyId='';
      }
      await postActionAsync(vm.url.saveValueTest + '?computeProjectLevel=' + computeProjectLevel+'&changeId='+this.changeId+ '&projectRewardApplyId=' + this.projectRewardApplyId, [vm.CoreAnswer])
        .then((res) => {
          this.showBtn = true
          if (res.code === 200) {
            if (type == 'pre' || type == 'next') {
              vm.changePage(type)
            } else if (type === 'fresh') {
              window.location.reload();
            } else if (type === 'save') {
              if (res.success) {
                vm.$message.success('保存成功')
                var result = res.result
                vm.projectLevel = result.projectLevel
                vm.projectGradePointCore = result.projectGradePointCore
                vm.judgeResult = true
                submitresult = 2
                vm.currGroupIndex=vm.questionList.length-1
                vm.currPageIndex=vm.questionList[vm.currGroupIndex].length-1
                vm.currStartQuestionId = vm.questionList[vm.currGroupIndex][vm.currPageIndex][0].id
                vm.hadNext = false
                if(vm.projectRewardApplyId){
                  vm.reloadOpener();
                }
              } else {
                vm.$message.warning('计算得分有误:' + res.message)
              }
            } else {
              vm.$message.success('保存成功')
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch((e) => {
          this.$message.warning('操作异常:' + e.message)
          this.showBtn = true
        })
        return submitresult;
    },
    reloadOpener(){
      if(window.parentReload){
        window.parentReload("{}")
      }else{
        window.opener.location.reload();
      }
    },
    async doSubmit(){
    console.log('------questionnairepageCore doSubmit--------')
    var questNull = this.coreGroupQuestionList==null || this.coreGroupQuestionList.length==0;
    if(questNull){
      console.log('------questionnairepage return--------questNull')
      return 2;
    }
    var approvalManagerEdit = this.projectBuild.status==2 && this.currentAudit;
    if(this.projectBuild.status>1 && !this.changeId && !approvalManagerEdit&& !this.projectRewardApplyId){
      console.log('------questionnairepage return--------questNull')
      return 2;
    }
    if(this.needReload||!this.canDoSave){
      console.log('------questionnairepage return--------needReload')
      return 2;
    }
    var verifyData = this.verifyData();
    console.log('verifyData:',verifyData);
    if (verifyData) {  
        return await this.saveAndNext('save')
      } else {
        console.log('------questionnairepage return--------!verifyData')
        return false;
      }
   },
    //下一步操作
    nextDo(type) {
      if(this.needReload){
        this.reloadVisible=true;
        return;
      }
      if((type == 'pre' || type == 'next') && this.checkQuestionChange()) {
        this.changePage(type)
        return;
      }
      if (this.verifyData()) {
        this.saveAndNext(type)
      } else {
        console.log(type + 'cancel,verifyData not pass')
      }
    },
    //检测题目是否变更
    checkQuestionChange() {
      if (this.oldQuestions.length != this.questionList.length) {
        return false
      }
      var flag = true
      //试题组比对
      for (var g = 0; g < this.oldQuestions.length; g++) {
        var oldgroup = this.oldQuestions[g]
        var group = this.questionList[g]
        if (oldgroup.length != group.length) {
          return (flag = false)
        }
        //每组下的页比对
        for (var p = 0; p < oldgroup.length; p++) {
          var oldpage = oldgroup[p]
          var page = group[p]
          if (oldpage.length != page.length) {
            return (flag = false)
          }
          //每页下的题目答案比对
          for (var q = 0; q < oldpage.length; q++) {
            var oldquest = oldpage[q]
            var quest = page[q]
            if (oldquest.valueTestId != quest.valueTestId) {
              return (flag = false)
            }
            var oldquestval = this.getQuestVal(oldquest)
            var questval = this.getQuestVal(quest)
            if (!(oldquestval == null && questval == null)) {
              if (oldquestval == null || questval == null) {
                return (flag = false)
              }
              if (JSON.stringify(oldquestval) != JSON.stringify(questval)) {
                return (flag = false)
              }
            }
            //文件比对
            var oldquestfiles = oldquest.sourceFileList
            var questfiles = quest.fileList
            if (!(!arrNotNull(oldquestfiles) && !arrNotNull(questfiles))) {
              if (!arrNotNull(oldquestfiles) || !arrNotNull(questfiles)) {
                return (flag = false)
              }
              if (oldquestfiles.length != questfiles.length) {
                return (flag = false)
              }
              for (var f = 0; f < oldquestfiles.length; f++) {
                var oldfile = oldquestfiles[f]
                var file = questfiles[f]
                if (!(oldfile.fileName==file.fileName && oldfile.uploadTime==file.uploadTime && oldfile.uploaderName==file.uploaderName)) {
                  return (flag = false)
                }
              }
            }
          }
          //说明比对
          if (quest.answerMemo != oldquest.answerMemo) {
            return (flag = false)
          }
        }
      }
      return flag
    },

    //验证操作
    verifyData() {
      var questionArr = this.questionList[this.currGroupIndex][this.currPageIndex]
      for (let i = 0; i < questionArr.length; i++) {
        let item = questionArr[i]
        let questNum = item.questionNum
        var msgPre = '第【' + item.orderNum + '】题'
        var fileListIsNull = item.fileList == null || item.fileList.length === 0
        var answerMemoIsNull = item.answerMemo == null || String(item.answerMemo) == ''
        var questionVal = this.getQuestVal(item)
        if (questionVal != null) {
          questionVal = questionVal.toString()
        }
        var questionValIsNull = questionVal == null || questionVal == '' || questionVal.length == 0
        //必答题判断
        if(item.requiredFlag&&questionValIsNull){
          document.getElementById(questNum).scrollIntoView(true)
          this.$message.warning(msgPre + '为必答题，请作答');
          return false
        }
        if (questionValIsNull && item.needAttachFlag && !fileListIsNull) {
          document.getElementById(questNum).scrollIntoView(true)
          this.$message.warning(msgPre + '已填写附件信息，请完成作答')
          return false
        }
        if (!questionValIsNull && item.needAttachFlag && fileListIsNull) {
          document.getElementById(questNum).scrollIntoView(true)
          this.$message.warning(msgPre + '已作答，请上传附件信息')
          return false
        }
        if (questionValIsNull && item.needAnswerMemoFlag && !answerMemoIsNull) {
          document.getElementById(questNum).scrollIntoView(true)
          this.$message.warning(msgPre + '已填写说明，请完成作答')
          return false
        }
        if (!questionValIsNull && item.needAnswerMemoFlag && answerMemoIsNull) {
          document.getElementById(questNum).scrollIntoView(true)
          this.$message.warning(msgPre + '已作答，请填写说明信息')
          return false
        }
      }
      return true
    },
    //清除该页该问题后的答题
    removeNextQuestions(questionId) {
      var vm = this
      var removeIndex = -1
      var currPage = vm.questionList[vm.currGroupIndex][vm.currPageIndex]
      for (var i = 0; i < currPage.length; i++) {
        var quest = currPage[i]
        if (quest.id == questionId) {
          removeIndex = i
        }
      }
      if (removeIndex > -1) {
        var removes = currPage.splice(removeIndex + 1)
        if (removes != null && removes.length > 0) {
          removes.forEach((quest) => {
            if (quest.needAttachFlag && quest.fileList.length > 0 && !this.changeId) {
              //删除附件
              vm.delFile(quest.id)
            }
          })
        }
      }
    },
    //切换页
    changePage(type) {
      if (type == 'pre') {
        if (this.currGroupIndex == 0) {
          if (this.currPageIndex > 0) {
            this.currPageIndex--
          }
        } else {
          if (this.currPageIndex == 0) {
            //当前组第一页，到上一组
            this.currGroupIndex--
            this.currPageIndex = this.questionList[this.currGroupIndex].length - 1
          } else {
            this.currPageIndex--
          }
        }
        this.hadNext = true
      } else if (type == 'next') {
        if (this.currGroupIndex == this.questionList.length - 1) {
          //最后一组
          this.currPageIndex++
          if (this.currPageIndex == this.questionList[this.currGroupIndex].length - 1) {
            //最后一页，跳转到时间表
            this.hadNext = false
          }
        } else {
          if (this.currPageIndex == this.questionList[this.currGroupIndex].length - 1) {
            //当前组最后一页,跳转下一组第一页
            this.currGroupIndex++
            this.currPageIndex = 0
            if (
              this.currGroupIndex == this.questionList.length - 1 &&
              this.questionList[this.currGroupIndex].length == 1
            ) {
              //最后一组，且该组只有一页
              this.hadNext = false
            }
          } else {
            this.currPageIndex++
          }
        }
      }
      this.currStartQuestionId = this.questionList[this.currGroupIndex][this.currPageIndex][0].id
      this.freshPreQustionList()
    },
    //初始化当前页跳转id
    freshPreQustionList() {
      this.preQuestionList = JSON.parse(JSON.stringify(this.questionList))
    },
    //获取下一页题目
    getNextPageQuestions(list, jumpId) {
      var questions = []
      var jumpQuestion = this.getQuestionFromSource(jumpId)
      if (jumpQuestion == null) {
        this.$message.warning('跳转问题id【' + jumpId + '】无效，请联系管理员 ')
        return questions
      }
      if (list != null && list.length > 0) {
        for (var i = 0; i < list.length; i++) {
          var quest = JSON.parse(JSON.stringify(list[i]))
          if (jumpQuestion.orderNum <= quest.orderNum) {
            questions.push(quest)
            if (this.hadNextQuestionType(quest.questionType) && !quest.relateTechnologyLibFlag) {
              for (var j = 0; j < quest.optionVoList.length; j++) {
                var option = quest.optionVoList[j]
                if (option.jumpQuestionId != null && option.jumpQuestionId > 0) {
                  //包含跳转的，为一页
                  return JSON.parse(JSON.stringify(questions))
                }
              }
            }
          }
        }
      }
      return JSON.parse(JSON.stringify(questions))
    },
    //有跳转的问题类型
    hadNextQuestionType(questionType) {
      if (questionType == 1 || questionType == 4) {
        //单选/判断题选项可能有跳转
        return true
      } else {
        return false
      }
    },
    //根据问题id从问题模板获取问题
    getQuestionFromSource(id) {
      var questionList = this.getQuestionListFromGroupList(this.coreGroupQuestionList)
      for (var i = 0; i < questionList.length; i++) {
        if (id === questionList[i].id) {
          return JSON.parse(JSON.stringify(questionList[i]))
        }
      }
      return null
    },
    getQuestionFromQuestionList(id) {
      var question = null
      this.questionList[this.currGroupIndex][this.currPageIndex].forEach((quest) => {
        if (quest.id == id) {
          question = quest
        }
      })
      return question
    },
    //把所有问题转入1个list中
    getQuestionListFromGroupList(groupList) {
      var list = []
      groupList.forEach((group) => {
        group.forEach((page) => {
          list = list.concat(page)
        })
      })
      return list
    },
    //清空问题
    clearnQuestion(id) {
      var quest = this.getQuestionFromQuestionList(id)
      if (quest == null) {
        this.$message.warning('获取问题失败')
        return
      }
      var valJump = false
      var val = this.getQuestVal(quest)
      quest.optionVoList.forEach((option) => {
        if (option.jumpQuestionId != null && option.jumpQuestionId > 0 && option.id == val) {
          valJump = true
        }
      })
      this.setQuestValNull(id)
      if (valJump) {
        this.removeNextQuestions(id)
        this.addJumpFresh = true
      }
      this.freshPreQustionList()
    },
    //将问题作答设置为空
    setQuestValNull(id) {
      this.questionList[this.currGroupIndex][this.currPageIndex].forEach((quest) => {
        if (quest.id == id) {
          quest.fileList = []
          quest.technologyList = []
          quest.answerMemo = ''
          quest.singleChoice = null
          quest.multipleChoice = null
          quest.answerValue = ''
          quest.trueOrFalse = null
        }
      })
    },
    //获取问题的值
    getQuestVal(item) {
      if (item.questionType === 1) {
        return item.singleChoice
      } else if (item.questionType === 2) {
        return item.multipleChoice
      } else if (item.questionType === 3 && !item.relateTechnologyLibFlag) {
        return item.answerValue
      } else if (item.questionType === 4) {
        return item.trueOrFalse
      }
      if (item.relateTechnologyLibFlag) {
        return item.technologyList
      }
      return null
    },
    //删除附件
    delFile(questionId) {
      if(this.changeId){
        return;
      }
      var url = '/tp/attach/delete'
      var param = {
        dbKey: 'Trd',
        ftpKey: 'ftp',
        busKey: this.changeId ? this.projectBuildId+'_'+this.changeId : this.projectBuildId,
        busField: this.changeId ? 'ProjectBuildValueChange' : 'ProjectBuildValue',
        busType: questionId,
      }
      postAction(url, param)
        .then((res) => {
          if (res.code != 200) {
            this.$message.warning(res.message)
          }
        })
        .catch((err) => {
          this.$message.error(`删除附件失败：${err.message}`)
        })
    },
    confirmJumpOk() {
      this.confirmVisible = false
      this.removeNextQuestions(this.confirmQuestionId)
      this.addJumpQuestion(this.confirmJumpId)
    },
    confirmJumpCancel() {
      this.confirmVisible = false
      this.resetJumpQuestion(this.confirmQuestionId, this.confirmOldOptionId)
    },
  },
  filters: {},
}
</script>
<style lang="less" scoped>
.value-page {
  ul,
  menu,
  dir {
    -webkit-margin-before: 0px;
    -webkit-margin-after: 0px;
    -webkit-padding-start: 0px;
  }
  width: 100%;
  // background-color: #f5f5f5;
  // padding-bottom: 70px;
  .judge-result {
    overflow: hidden;
    padding: 11px 0;
    margin-bottom: 15px;
    border: 1px solid rgb(237, 237, 237);
    background-color: #fff;
    div {
      text-align: center;
      float: left;
    }
    .result-show {
      font-size: 16px;
      color: red;
    }
  }

  .classify-header {
    color: #fff;
    .header-bg {
      height: 100px;
      background-image: url('../assets/value-bg.png');
      background-size: contain;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background-repeat: repeat-x;
      .header-step {
        padding: 35px 0 0 50px;
        font-size: 14px;
        display: flex;
        > div {
          flex: 1;
          display: flex;
          align-items: center;
          vertical-align: center;
          // justify-content: space-between;
          // padding-right: 20px;
          width: 16%;
        }
        i {
          font-style: normal;
          display: inline-block;
          text-align: center;
          width: 100%;
        }
        .step-style {
          display: inline-block;
          width: 80px;
          height: 6px;
          border-radius: 10px 0 0 10px;
          // margin-right: 35px;
          position: relative;
          &::before {
            position: absolute;
            content: '';
            right: -2px;
            top: -80%;
            width: 16px;
            height: 16px;
            border-radius: 50%;
          }
        }
        .step-unfinished {
          color: #fff;
          .step-style {
            background-color: #fff;
            &::before {
              background-color: inherit;
            }
          }
        }
        .step-finished {
          color: #6ca8f8;
          .step-style {
            background-color: #6ca8f8;
            &::before {
              background-color: inherit;
            }
          }
        }
      }
      .header-warn {
        padding: 0 150px;
        position: absolute;
        bottom: 12%;
        // left: 10%;
        font-weight: 600;
        img {
          width: 18px;
          vertical-align: middle;
          margin-right: 5px;
          margin-top: -2px;
        }
        span {
          font-weight: normal;
          font-size: 10px;
          opacity: 0.8;
        }
      }
    }
  }
  input {
    margin: 5px 0;
  }
  .question-list {
    padding: 20px 0px 50px 0px;
    height: fit-content;
    background-color: #f5f5f5;
    .btnBox {
      text-align: center;
      display: block;
      border: unset;
      & /deep/ .ant-btn {
        border: unset;
        border-radius: unset;
        margin: 0 20px;
        width: 150px;
      }
      & /deep/ .ant-btn-primary {
        background-color: #24508c;
      }
    }
    /deep/ .ant-tabs-nav-container {
      margin-top: 0;
    }
    /deep/ .ant-tabs .ant-tabs-left-bar {
      border-right: none;
    }
    /deep/ .ant-tabs .ant-tabs-left-bar .ant-tabs-tab {
      text-align: left;
      width: 201px;
      border-bottom: 1px dashed #e9e9e9;
      margin: 0;
      padding: 15px 25px;
      transition: none;
      &::after {
        content: '';
        background: url('../assets/unselected.png') no-repeat;
        width: 6px;
        height: 10px;
        float: right;
        margin-top: 5px;
      }
    }
    /deep/ .ant-tabs-nav .ant-tabs-tab:active,
    /deep/ .ant-tabs-nav .ant-tabs-tab-active {
      color: #fff;
      background-color: #4790bb;
      &::after {
        content: '';
        background: url('../assets/selected.png') no-repeat;
      }
    }
    /deep/ .ant-tabs .ant-tabs-left-bar .ant-tabs-tab:focus {
      &::after {
        content: '';
        background: url('../assets/selected.png') no-repeat;
      }
    }
    /deep/ .ant-tabs-ink-bar {
      background-color: inherit;
      opacity: 0;
    }
    /deep/.ant-tabs .ant-tabs-left-content {
      border: none;
      max-width: 80%;
    }
    /deep/.ant-tabs .ant-tabs-left-content {
      overflow: unset;
    }
  }
}
.floatNav{position: fixed; top: 380px; left: 30px;z-index:1;}
@media (max-width: 1080px) {
  .floatNav{left:5px;
    button{padding: 0 2px;font-size: 12px;}
  }
}
</style>